<?php

declare(strict_types=1);

namespace app\controller\system\notify;

use app\BaseController;
use app\model\NotifyTemplate;
use app\service\factory\ResponseFactory;
use app\service\notify\TemplateService;
use app\validate\notify\TemplateValidate;
use InvalidArgumentException;
use think\Response;
use Throwable;

class Template extends BaseController
{
    public function index(TemplateService $templateService): Response
    {
        try {
            $page = max(1, (int) $this->request->param('page', 1));
            $pageSize = (int) $this->request->param('page_size', 20);
            $pageSize = $pageSize > 0 ? min($pageSize, 100) : 20;

            $filters = $this->request->only([
                'keyword',
                'status',
                'category',
                'type',
            ], 'get');

            $paginator = $templateService->paginate($filters, $page, $pageSize);

            $items = array_map(
                static fn(NotifyTemplate $template) => $templateService->format($template),
                $paginator->items()
            );

            return json(ResponseFactory::paginated(
                $items,
                (int) $paginator->total(),
                $page,
                $pageSize
            ));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }

    public function save(TemplateService $templateService): Response
    {
        try {
            $payload = $this->request->only([
                'name',
                'title',
                'content',
                'type',
                'category',
                'channels',
                'status',
            ], 'post');

            $this->validate($payload, TemplateValidate::class . '.create');

            $template = $templateService->create($payload);

            return json(ResponseFactory::success($templateService->format($template), '模板已创建'));
        } catch (InvalidArgumentException $e) {
            return json(ResponseFactory::error($e->getMessage(), 422));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }

    public function read(int $id, TemplateService $templateService): Response
    {
        try {
            $template = $templateService->findById($id);
            if (!$template) {
                return json(ResponseFactory::error('模板不存在', 404));
            }

            return json(ResponseFactory::success($templateService->format($template)));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }

    public function update(int $id, TemplateService $templateService): Response
    {
        try {
            $template = NotifyTemplate::find($id);
            if (!$template) {
                return json(ResponseFactory::error('模板不存在', 404));
            }

            $payload = $this->request->only([
                'name',
                'title',
                'content',
                'type',
                'category',
                'channels',
                'status',
            ], 'put');
            $payload['id'] = $id;

            $this->validate($payload, TemplateValidate::class . '.update');

            $updated = $templateService->update($template, $payload);

            return json(ResponseFactory::success($templateService->format($updated), '模板已更新'));
        } catch (InvalidArgumentException $e) {
            return json(ResponseFactory::error($e->getMessage(), 422));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }

    public function delete(int $id, TemplateService $templateService): Response
    {
        try {
            $template = NotifyTemplate::find($id);
            if (!$template) {
                return json(ResponseFactory::error('模板不存在', 404));
            }

            if (!$templateService->delete($template)) {
                return json(ResponseFactory::error('删除失败', 500));
            }

            return json(ResponseFactory::success(true, '模板已删除'));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }
}
